<html>
<head>
<title>Setup report</title>
</head>
<body>
Setup in progress...
<br />
<?php
//---------------------------------------------------------------------------
// Database creation functions
//---------------------------------------------------------------------------
/**
 * Open the database and return a connection
 * @param string $p_dbHost the database host name
 * @param string $p_dbSetupUser the database SETUP user name
 * @param string $p_dbSetupPassword the database SETUP user password
 * @return MySQLI
 */
function openDatabase($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword){
	//Create the database
	$mysqli = new mysqli($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword);

	//Check connection
	if (mysqli_connect_errno()) {
		printf("Database connect failed: %s\n", mysqli_connect_error());
		exit();
	}
	return $mysqli;
}

/*
 CREATE SCHEMA IF NOT EXISTS `iatb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
 */

/**
 * Create the database schema and the tables in the database
 * @param string $p_dbHost the database host name
 * @param string $p_dbSetupUser the database SETUP user name
 * @param string $p_dbSetupPassword the database SETUP user password
 * @param string $p_dbName the name of the RUNTIME database to be created
 * @return array an array of error messages
 */
function createTables($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword,$p_dbName){
	$l_errors=array();
	$mysqli = openDatabase($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword);

	//Load SQL create script
	$l_sqlScript=file_get_contents("dbcreate.sql");
	$l_sqlScript=str_replace("iatb",$p_dbName,$l_sqlScript);
	if(!$mysqli->multi_query($l_sqlScript)){
		$l_errors[]="Table creation error: %s\n" . $mysqli->error;
	}else{
		echo("- Tables created<br/>");
	}

	$mysqli->close();

	return $l_errors;
}

/**
 * Create the reference data (example: Activity types)
 * @param string $p_dbHost the database host name
 * @param string $p_dbSetupUser the database SETUP user name
 * @param string $p_dbSetupPassword the database SETUP user password
 * @param string $p_dbName the name of the RUNTIME database to be created
 * @param array $p_activityTypes an array of string (= activity labels)
 * @return array an array of error messages
 */
function createReferenceData($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword,$p_dbName, $p_activityTypes){
	$l_errors=array();
	$mysqli = openDatabase($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword);

	$l_count=0;
	foreach($p_activityTypes as $l_activityTypeLabel){
		if ($stmt = $mysqli->prepare("INSERT INTO {$p_dbName}.activitytype (id,label) values (?,?)")) {
			$stmt->bind_param("is", $l_count, $l_activityTypeLabel);
			if(!$stmt->execute()){
				$l_errors[]="Unable to create the reference data: %s\n" . $mysqli->error;
			}
			$stmt->close();
		}else{
			$l_errors[]="Unable to create the reference data: %s\n" . $mysqli->error;
		}
		$l_count++;
		echo("- Activity type: " . $l_activityTypeLabel . " created !<br/>");
	}
	$mysqli->close();

	return $l_errors;
}

/**
 * Create the runtime user
 * @param string $p_dbHost the database host name
 * @param string $p_dbSetupUser the database SETUP user name
 * @param string $p_dbSetupPassword the database SETUP user password
 * @param string $p_dbRuntimeUser the database RUNTIME user name
 * @param string $p_dbRuntimePassword the database RUNTIME user password
 * @param string $p_dbName the name of the RUNTIME database to be created
 * @return array an array of error messages
 */
function createRuntimeUser($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword,$p_dbRuntimeUser,$p_dbRuntimePassword,$p_dbName){
	$l_errors=array();
	$mysqli = openDatabase($p_dbHost, $p_dbSetupUser, $p_dbSetupPassword);

	$l_sqlStatement="create user {$p_dbRuntimeUser} identified by '{$p_dbRuntimePassword}';";
	if(!$mysqli->query($l_sqlStatement)){
		echo("- WARNING: user creation failed<br/>");
		echo("<i>Error Message: %s\n" . $mysqli->error . "</i><br/>");
	}else{
		echo("- RUNTIME user created<br/>");
	}

	$l_sqlStatement="grant SELECT, INSERT, DELETE, UPDATE on {$p_dbName}.* to '{$p_dbRuntimeUser}'";
	if(!$mysqli->query($l_sqlStatement)){
		echo("- WARNING: unable to grant rights to database user<br/>");
		echo("<i>Error Message: %s\n" . $mysqli->error . "</i><br/>");
	}else{
		echo("- RUNTIME user allocated with database rights<br/>");
	}
	$mysqli->close();

	return $l_errors;
}


/**
 * Generate a the "conf.php" configuration file
 * @param string $p_rootPath the root path for the application
 * @param string $p_dbHost the database host name
 * @param string $p_dbRuntimeUser the database RUNTIME user name
 * @param string $p_dbRuntimePassword the database RUNTIME user password
 * @param string $p_dbName the name of the RUNTIME database to be created
 * @param string $p_dbFilePath the log file path
 * @return array an array of error messages
 */
function generateConfigurationFile($p_rootPath,$p_dbHost,$p_dbRuntimeUser,$p_dbRuntimePassword,$p_dbName,$p_dbFilePath){
	$l_errors=array();
$fileContent=<<<EOT
<?php
	//Additional include for shared hosting
	//ini_set('include_path', ini_get('include_path') . ':/home.10.26/pycloux/pear/');

	//The root directory in which the application is installed
	define("ROOT_PATH","${p_rootPath}");
	define("LOG_FILE","${p_dbFilePath}");

	//Database configuration file
	define("__DB_USER","${p_dbRuntimeUser}");
	define("__DB_PASSWORD","${p_dbRuntimePassword}");
	define("__DB_URL","mysql:host=${p_dbHost};dbname=${p_dbName}");
	
	//Plugins variables
	define("HTPASSWD_FILE_PATH","E:/Development/NewWorkspace/IATBProjectCheckout/htdocs/.htpasswd_test");
	
	//Footer disclamer
	define("FOOTER_DISCLAIMER","Department name, (c) Company 2008");
?>
EOT;

	if(!file_put_contents("conf.php",$fileContent)){
		$l_errors[]="Unable to write the configuration file";
	}
	return $l_errors;
}

/**
 * Unactivate the setup script (rename)
 */
function unactivateSetup(){
	rename("setup.php","setup.old");
	rename("start.php","start.old");
}

//---------------------------------------------------------------------------
// Setup script
//---------------------------------------------------------------------------

//Errors
$l_errors=array();

//Validate the inputs
$l_rootPath=$_REQUEST["tfRootPath"];
if(!isset($l_rootPath)){
	$l_errors[]="Empty Root Path parameter";
}
$l_dbHost=$_REQUEST["tfDbHost"];
if(!isset($l_dbHost)){
	$l_errors[]="Empty database host parameter";
}
$l_dbName=$_REQUEST["tfDbName"];
if(!isset($l_dbName)){
	$l_errors[]="Empty database name parameter";
}
$l_dbSetupUser=$_REQUEST["tfDbSetupUser"];
if(!isset($l_dbSetupUser)){
	$l_errors[]="Empty database SETUP user name parameter";
}
$l_dbSetupPassword=$_REQUEST["tfDbSetupPassword"];
$l_dbRuntimeUser=$_REQUEST["tfDbRuntimeUser"];
if(!isset($l_dbRuntimeUser)){
	$l_errors[]="Empty database RUNTIME user name parameter";
}
$l_dbRuntimePassword=$_REQUEST["tfDbRuntimePassword"];
$l_dbFilePath=$_REQUEST["tfLogFilePath"];
if(!isset($l_dbFilePath)){
	$l_errors[]="Empty log file path parameter";
}

$l_activityTypes=trim($_REQUEST["tfActivityTypes"]);
if(!isset($l_activityTypes)){
	$l_errors[]="Please provide at least one activity type";
}

//Run scripts
if(count($l_errors)==0){
	$l_errors=createTables($l_dbHost,$l_dbSetupUser,$l_dbSetupPassword,$l_dbName);
}
if(count($l_errors)==0){
	$l_errors=createReferenceData($l_dbHost,$l_dbSetupUser,$l_dbSetupPassword,$l_dbName, explode(",",$l_activityTypes));
}
if(count($l_errors)==0){
	$l_errors=createRuntimeUser($l_dbHost,$l_dbSetupUser,$l_dbSetupPassword,$l_dbRuntimeUser,$l_dbRuntimePassword,$l_dbName);
}
if(count($l_errors)==0){
	$l_errors=generateConfigurationFile($l_rootPath,$l_dbHost,$l_dbRuntimeUser,$l_dbRuntimePassword,$l_dbName,$l_dbFilePath);
}

//Script ended, display the status
if(count($l_errors)!=0){
	?>
<b>Some errors have been reported</b>

<ul>
<?php
foreach($l_errors as $l_error){
	echo("<li>" . $l_error . "</li>");
}
}else{
	?>
	<b>Setup completed successfully !</b>
	<p>Please now connect to your server and move the "conf.php" file to
	the directory "apps/resources" (relative to your installation path).</p>
	<?php
	unactivateSetup();
}
?>
</ul>
</body>
</html>
